package com.shawn.dubbo.api;

import com.shawn.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi{

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    @Transactional
    public void save(Long userId, Long friendId) {
        checkAndSave(userId, friendId);
        checkAndSave(friendId, userId);

    }

    @Override
    public List<Friend> getAllById(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        return mongoTemplate.find(query,Friend.class);
    }

    private void checkAndSave(Long userId, Long friendId) {
        //为了防止数据重复,添加关系前,保证不存在重复数据
        Query userQuery = new Query();
        userQuery.addCriteria(Criteria.where("userId").is(userId))
                .addCriteria(Criteria.where("friendId").is(friendId));
        boolean res1 = mongoTemplate.exists(userQuery, Friend.class);
        if (!res1) {
            //保存该用户朋友数据
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }
}
